<?php
/**
 * @version		$Id: manager.php 10381 2008-06-01 03:35:53Z yopensource $
 * @package		Feeds manager
 * @subpackage	Link Manager
 * @license		commercial
 * @author 		yopensource
 * @email		yopensource@gmail.com
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport('joomla.application.component.model');

// Set the table directory
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

/**
 * Weblinks Component Weblink Model
 *
 * @package		Joomla
 * @subpackage	Content
 * @since 1.5
 */
class FVBModelMedias extends JModel
{
	/**
	 * amMap data array
	 *
	 * @var array
	 */
	var $_data = null;	

	/**
	 * uri total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;
	/**
	 * job
	 *
	 * @var array
	 */
	var $_job	=	null;
	/**
	 * list
	 *
	 * @var array
	 */
	var $list	=	null;

	/**
	 * Constructor
	 *
	 * @since 0.9
	 */
	function __construct()
	{
		parent::__construct();

		global $mainframe,$option;
		
		//$context			= 'com_content.viewcontent';
		$filter_order		= $mainframe->getUserStateFromRequest( $option.'.feeds_manager.filter_order', 'filter_order','id','cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.feeds_manager.filter_order_Dir',	'filter_order_Dir',	'','word' );		
		$search 			= $mainframe->getUserStateFromRequest( $option.'.feeds_manager.search', 'search','','string' );
		$search 			= JString::strtolower( $search );		
		
		$cms				= $mainframe->getUserStateFromRequest( $option.'.feeds_manager.cms',			'cms',			"",	'string' );	
		$links				= $mainframe->getUserStateFromRequest( $option.'.feeds_manager.links',			'links',			0,	'int' );	
		
		$limit				= $mainframe->getUserStateFromRequest($option.'.feeds_manager.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart			= $mainframe->getUserStateFromRequest($option.'.feeds_manager.limitstart', 'limitstart', 0, 'int');
		
		$this->setState('limit', 		$limit);
		$this->setState('limitstart', 	$limitstart);
		$this->setState('cms',$cms);
		$this->setState('links',$links);
		$this->setState('search', 		$search);
		// Get the filter request variables
		$this->setState('filter_order', 	$filter_order);
		$this->setState('filter_order_dir', $filter_order_Dir);
	}
	
	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery(); 
			$this->_total = $this->_getListCount($query);	
		}
		return $this->_total;
	}
	
	function getPagination()
	{		
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}	
		return $this->_pagination;
	}
	
	
	function getData(){	
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			
			$db=JFactory::getDBO();
			
			$db->setQuery($query,$this->getState('limitstart'), $this->getState('limit'));	
//			die();
			$data = $db->loadObjectList();
			
			$this->_data=$data;
		}		
		return $this->_data;
	}
	
	function _buildQuery(){
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildWhere();
		$orderby	= $this->_buildOrderBy();
		
		$config 	= &JComponentHelper::getParams('com_feed_manager');
		$data_type 	= $config->get('data_type');
		//Get Events from Database
		$query = ' SELECT ynj.id,ynj.title,ynj.cms,ynj.checked_out,ynj.checked_out_time,
					ynj.published,ynj.error_counter,ynj.last_update,ynj.time_update,ync.link,ync.id as link_id
					FROM #__FVB_crawler_jobs AS ynj 
						LEFT JOIN #__FVB_crawler AS ync 
						ON ynj.link_id=ync.id
					'. $where.
					 $orderby;
		return $query;
	}
	
	function _buildWhere( )
	{		
		$db					= &JFactory::getDBO();		
		$search				= $this->getState('search');
		$cms					=	$this->getState('cms');
		$links					=	$this->getState('links');
			
		$where 				= array();
		
		if ( $search ) {
			$where[] = 'ynj.title LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		// cms filter
		if ($cms) {
			$where[] = 'cms = ' . $db->Quote($cms);
		}
		if ($links) {
			$where[] = 'ync.id = ' . $db->Quote($links);
		}
		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );					
		return $where;
	}
	
	function _buildOrderBy()
	{
		$filter_order		=	$this->getState('filter_order');
		$filter_order_Dir	=	$this->getState('filter_order_dir');
		
		if ($filter_order == 'id'){
			$orderby 	= ' ORDER BY id';
		} else {
			$orderby 	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir .', id';
		}
		
		return $orderby;
	}
	
	function getLists(){
		
		// state filter
		$lists['state'] = JHTML::_('grid.state', $this->getState('filter_state'), 'Published', 'Unpublished');
		
		// table ordering
		$lists['order_Dir']	= $this->getState('filter_order_dir');
		$lists['order']		= $this->getState('filter_order');
		
		// search filter
		$lists['search']= $this->getState('search');
		
		$filter		= null;
		$filter_sectionid		=	$this->getState('sectionid');
		
		$config 	= &JComponentHelper::getParams('com_feed_manager');
		$data_type 	= $config->get('data_type');
		
		$arrCms=array();
		$arrFolder=JFolder::listFolderTree(JPATH_COMPONENT.DS.'cms','',1);
		foreach ($arrFolder as $value) {
			$cms=new stdClass();
			$cms->text=ucfirst($value['name']);
			$cms->value=$value['name'];
			$arrCms[]=$cms;
		}
			$active=$this->getState('cms');
			$option[] 	= JHTML::_('select.option', '0', '- '.JText::_('Select cms').' -');
			$option = array_merge($option, $arrCms);			
			$cms = JHTML::_('select.genericlist',  $option, 'cms', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $active);		
		$lists['cms']=$cms;
		
		$db=JFactory::getDBO();
		$query='SELECT id as value,link as text 
				FROM `#__FVB_crawler`';
		$db->setQuery($query);
		$arrLink=$db->loadObjectList();
		$active=$this->getState('links');
		$opt[] 	= JHTML::_('select.option', '0', '- '.JText::_('Select link').' -');
		$opt = array_merge($opt, $arrLink);			
		$links = JHTML::_('select.genericlist',  $opt, 'links', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $active);		
		$lists['links']=$links;
	
		return $lists;
	}
	function getCms_config_job(& $cmsName)
	{
		$this->getJob();
		$data=$this->_job->params ? $this->_job->params : "";
		
		$cmsName=JRequest::getVar('cms');
		
		$bool=JFile::exists(JPATH_COMPONENT.DS.'cms'.DS.$cmsName.DS.'cms_config_job.xml');
		if ($cmsName==null || $bool==false) {
			return null;
		}		
		$item_params    = new JParameter("",JPATH_COMPONENT.DS.'cms'.DS.$cmsName.DS.'cms_config_job.xml'); 
		$item_params->bind($data);
		
		$item_params->render();
		return $item_params;
	}
	function getJob()
	{
		global $mainframe;
		$option		= JRequest::getCmd( 'option' );
		if ($this->_job) {
			return $this->_job;
		}
		$j_row=& JTable::getInstance('FVB_crawler_jobs','Table');
		$cid=JRequest::getVar('cid','','','array');
		$j_row->load($cid[0]);	
		$this->_job=$j_row;
		$user 		=& JFactory::getUser();
		if ( JTable::isCheckedOut($user->get ('id'), $j_row->checked_out )) {
			$msg = JText::_(" \" $j_row->title \" is currently being edited by another administrator");
			$mainframe->redirect( "index.php?option=$option&task=jobmanager", $msg );
		}
		if($cid[0])
		{
			$j_row->checkout( $user->get('id'));
		}
		return $this->_job;
	}
	function getList_edit()
	{
		if ($this->list) {
			return $this->list;
		}
		$list=array();
		$list['links']=$this->getLinks();
		$list['cms']=$this->getCms();
//		$created_by=$this->_job->created_by;
		$list['created_by']		=	JHTML::_('list.users', 'created_by',0);		
		
		$this->list=$list;
		
		return $this->list;
	}
	function getCms()
	{
		$arrCms=array();
		$arrFolder=JFolder::listFolderTree(JPATH_COMPONENT.DS.'cms','',1);
		foreach ($arrFolder as $value) {		
			$cms=new stdClass();
			$cms->name=ucfirst($value['name']);
			$cms->value=$value['name'];
			$arrCms[]=$cms;
		}		
		$active=0;
		if ($this->_job)
			$active=$this->_job->cms;
		$cms = JHTML::_('select.genericlist',  $arrCms, 'cms', 'class="inputbox" size="1"', 'value', 'name', $active);		
		return $cms;
	}
	function getLinks()
	{
		$active=0;
		if ($this->_job)
			$active=$this->_job->link_id;
			
		$db=JFactory::getDBO();
		$query='SELECT id,link
				FROM #__FVB_crawler 
				ORDER BY id DESC';
		$db->setQuery($query);
		$data=$db->loadObjectList();
		$links = JHTML::_('select.genericlist',  $data, 'link_id', 'class="inputbox" size="1"', 'id', 'link', $active);		
		return $links;		
	}
	function getScript(){
		
		$script=
		"
			google.load(\"language\", \"1\");
			google.setOnLoadCallback(init);
			
			function init() 
			{				
				var t_from = document.getElementById('t_from');
				var t_to = document.getElementById('t_to');
				for (l in google.language.Languages) 
				{
					var lng = l.toLowerCase();
					lng 		= lng.substring(0,1).toUpperCase()+lng.substring(1,lng.length);
					var lngCode = google.language.Languages[l];
					if (google.language.isTranslatable(lngCode)) 
					{
						t_from.options.add(new Option(lng, lngCode));
						t_to.options.add(new Option(lng, lngCode));
					}
				}
			}";
		return $script;
	}
}